import {
  getPickingDetailsByPage,
  addPickingDetails,
  updatePickingDetails,
  addMaterialQty,
  exportPickingDetails,
} from '@/services/product/pickingDetails';
import { scanSerNo, allocation } from '@/services/product/pickingTask';
import { EditOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Form, Input, message, InputNumber } from 'antd';
import { sortTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
const PickingDetails = React.forwardRef((props, ref) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const [editingCell, setEditingCell] = useState(null); // 使用state跟踪编辑状态
  const [inputValue, setInputValue] = useState<number>();

  const refs = useRef(null);
  const inputRef = useRef(null);
  const [serialNumValue, setSerialNumValue] = useState('');
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
      align: 'center',
      sorter: true,
    },
    {
      title: '物料编号',
      align: 'center',
      sorter: true,
      dataIndex: 'materialCode',
      width: 80,
    },
    {
      title: '到货日期',
      align: 'center',
      sorter: true,
      dataIndex: 'deliveryDate',

      render: (text) => {
        return text != '-' ? text : '#';
      },
      width: 80,
    },
    {
      title: '物料名称',
      align: 'center',
      sorter: true,
      dataIndex: 'materialName',

      width: 80,
    },
    {
      title: '物料规格',
      align: 'center',
      sorter: true,
      dataIndex: 'materialSpec',
      width: 80,
    },
    {
      title: '单位',
      align: 'center',
      sorter: true,
      dataIndex: 'unit',

      width: 50,
    },

    {
      title: '产品编号',
      align: 'center',
      sorter: true,
      dataIndex: 'partCode',
      hideInTable: true,
      width: 80,
    },
    {
      title: '位置号',
      align: 'center',
      sorter: true,
      dataIndex: 'positionNo',

      width: 50,
    },
    {
      title: '需求数量',
      align: 'center',
      sorter: true,
      dataIndex: 'materialQty',
      width: 80,
    },
    {
      title: '本次数量',
      align: 'center',
      sorter: true,
      dataIndex: 'thistimeQty',
      width: 60,
    },
    {
      title: '实际数量',
      align: 'center',
      sorter: true,
      dataIndex: 'outboundQty',

      width: 80,
    },
    {
      title: '未分数量',
      align: 'center',
      sorter: true,
      dataIndex: 'notIssuedQty',
      width: 80,
    },
    {
      title: '物料分类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialClassification',
      width: 80,
    },
    {
      title: '物料种类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialType',
      width: 80,
    },
    {
      title: '是否甲供',
      align: 'center',
      sorter: true,
      dataIndex: 'isJia',
      width: 80,
    },
    {
      title: '序列号',
      align: 'center',
      sorter: true,
      dataIndex: 'serialNum',
      width: 120,
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createTime',

      width: 80,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',

      width: 60,
    },
/*     {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="scan"
          onClick={async () => {
            const result = await addMaterialQty({
              materialCode: record.materialCode,
              pickingTaskCode: record.pickingTaskCode,
            });

            if (result && result.code === 0) {
              message.success(result.message);
            }
          }}
        >
          扫描
        </a>,
      ],
    }, */
  ];

  React.useEffect(() => {
    setInputValue(Number(inputValue));
  }, [inputValue]);

  const handleQtyChange = (record: any, value: any) => {
    if (Number(value) <= record.materialQty) {
      // 在这里处理修改后的值
      setInputValue(Number(value));
      record.notIssuedQty = record.materialQty - Number(value);
    } else {
      message.info('已发数量不能大于需求数量');
    }
  };

  const columns1: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '物料名称',
      align: 'center',
      sorter: true,
      dataIndex: 'materialName',

      width: 100,
    },
    {
      title: '物料规格',
      align: 'center',
      sorter: true,
      dataIndex: 'materialSpec',
      width: 100,
    },
    {
      title: '是否变更',
      align: 'center',
      sorter: true,
      dataIndex: 'isChanged',
      render: (text) => {
        return text == 0 ? '否' : '是';
      },
      width: 60,
    },
    {
      title: '单位',
      align: 'center',
      sorter: true,
      dataIndex: 'unit',
      width: 60,
    },
    {
      title: '产品编号',
      align: 'center',
      sorter: true,
      dataIndex: 'partCode',
      hideInTable: true,
      width: 100,
    },
    {
      title: '位置号',
      align: 'center',
      sorter: true,
      dataIndex: 'positionNo',
      width: 60,
    },
    {
      title: '需求数量',
      align: 'center',
      sorter: true,
      dataIndex: 'materialQty',
      width: 60,
    },
    {
      title: '未分数量',
      align: 'center',
      sorter: true,
      dataIndex: 'notIssuedQty',
      width: 60,
      render: (text, record) => {
        // if (editingCell === record.id) {
        //   return notQty !== -1 ? notQty : 0;
        // } else {
        //   return text;
        // }
        return text;
        // return notQty !== -1 ? notQty : text;
      },
    },
    {
      title: '已分数量',
      align: 'center',
      sorter: true,
      dataIndex: 'outboundQty',
      width: 60,
      render: (text, record) => {
        if (editingCell === record.id) {
          // 编辑状态下显示InputNumber
          return (
            <InputNumber
              value={record.outboundQty}
              min={0}
              step={1} // 设置步进值为1
              onChange={(value) => handleQtyChange(record, value)}
              onBlur={() => setEditingCell(null)} // 失去焦点时取消编辑状态
              // onPressEnter={() => setEditingCell(null)} // 按下回车键时取消编辑状态
              onPressEnter={async () => {
                const temp: any = record;
                temp.outboundQty = inputValue;
                if (temp.outboundQty === '') {
                  //数量不为空才提交
                  message.error('未输入已发数量');
                } else if (temp.outboundQty % 1 != 0) {
                  message.error('已发数量必须为整数');
                } else {
                  const result = await allocation(temp);
                  if (result?.code == 0) {
                    message.success('分料成功');
                    setEditingCell(null);
                  }
                  actionRef.current!.reload();
                }
              }}
              autoFocus // 自动获取焦点
            />
          );
        } else {
          return (
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => setEditingCell(record.id)} // 点击时设置编辑状态
            >
              {text}
              <EditOutlined style={{ color: 'green' }} />
            </span>
          );
        }
      },
    },
    {
      title: '物料分类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialClassification',
      width: 80,
    },
    {
      title: '物料种类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialType',
      width: 80,
    },
    {
      title: '是否甲供',
      align: 'center',
      sorter: true,
      dataIndex: 'isJia',
      width: 80,
    },
    {
      title: '序列号',
      width: 100,
      align: 'center',
      sorter: true,
      dataIndex: 'serialNum',
      render: (text, record) => {
        // 编辑状态下显示Input框框
        return (
          <Input
            ref={inputRef}
            onChange={(e) => {
              setSerialNumValue(e.target.value);
            }}
            onBlur={async (e) => {
              const temp: any = record;
              temp.serialNum = serialNumValue;
              if (temp.serialNum === '') {
                //序列号不为空才提交
                message.error('未输入序列号');
              } else {
                const result = await scanSerNo(temp);
                if (result?.code == 0) {
                  message.success('扫描序列号成功');
                }
                setSerialNumValue(''); //重置序列号值为空
                actionRef.current!.reload();
              }
            }}
            onPressEnter={async () => {
              const temp: any = record;
              temp.serialNum = serialNumValue;
              if (temp.serialNum === '') {
                //序列号不为空才提交
                message.error('未输入序列号');
              } else {
                const result = await scanSerNo(temp);
                if (result?.code == 0) {
                  message.success('扫描序列号成功');
                }
                setSerialNumValue(''); //重置序列号值为空
                actionRef.current!.reload();
              }
            }}
          />
        );
      },
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      width: 100,

      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      width: 60,
      align: 'center',
      sorter: true,

      dataIndex: 'createName',
    },
  ];

  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addPickingDetails(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updatePickingDetails(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current!.reload();
  };
  useImperativeHandle(ref, () => {
    return actionRef.current!.reload();
  });
  return (
    <>
      <ProTable
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={refs}
        search={false}
        onRow={() => ({
          onClick: (a) => {
            a.stopPropagation();
            console.log(a, 'a');
            let s = a.target.parentNode.parentNode.children;
            console.log(s);
            // 先重置为默认样式
            for (var i = 0; i < s.length; i++) {
              s[i].style.color = '#000000d9';
              s[i].style.fontWeight = 'normal';
              s[i].style.backgroundColor = '#fff';
            }
            // 再设置高亮样式
            a.target.parentNode.style.color = '#13C2C2';
            a.target.parentNode.style.fontWeight = 'bold';
            a.target.parentNode.style.backgroundColor = '#e6fffb';
          },
        })}
        request={async (params = {}, sort, filter) => {
          if (props.pickingTaskCode === undefined) {
            return {
              data: undefined,
            };
          }
          const sorters = sortTran(sort);
          const filters = [
            {
              andOr: 'and',
              field: 'pickingTaskCode',
              operator: 'eq',
              value: props.pickingTaskCode,
            },
          ];
          const result = await getPickingDetailsByPage({
            current: 1,
            pageSize: 5000,
            sorters: sorters,
            filters: filters,
          });
          let temp: any[] = [];
          if (result && result.data && result.data.content) {
            if (props.finishCode) {
              temp = result.data.content.filter((item: any) => item.notIssuedQty === 0);
            } else if (props?.state && props.state == 3) {
              temp = result.data.content;
            } else if (props?.state && props.state == 1) {
              //未分
              temp = result.data.content.filter((item: any) => item.notIssuedQty != 0);
            } else if (props?.state && props.state == 2) {
              // 已分
              temp = result.data.content.filter(
                (item: any) => item.outboundQty == item.materialQty,
              );
            }
          }
          temp.map((t) => {
            //将serialNumGroup的值赋给serialNum进行展示
            t.serialNum = t.serialNumGroup;
          });
          return {
            data: temp,
            // total: result.data.totalElements,
            total: temp.length,
            success: result.success,
          };
        }}
        columns={props?.state == 1 ? columns1 : columns}
        scroll={{ x: 2000, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="materialCode"
          label="物料编号"
          rules={[{ required: true, message: 'Please input your materialCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialName"
          label="物料名称"
          rules={[{ required: true, message: 'Please input your materialName!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialQty"
          label="物料数量"
          rules={[{ required: true, message: 'Please input your materialQty!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialSequence"
          label="物料序号"
          rules={[{ required: true, message: 'Please input your materialSequence!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialSpec"
          label="规格"
          rules={[{ required: true, message: 'Please input your materialSpec!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="memo"
          label="备注"
          rules={[{ required: true, message: 'Please input your memo!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="notIssuedQty"
          label="未分数量"
          rules={[{ required: true, message: 'Please input your notIssuedQty!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="outboundQty"
          label="已发数量"
          rules={[{ required: true, message: 'Please input your outboundQty!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="partCode"
          label="产品编号"
          rules={[{ required: true, message: 'Please input your partCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="pickingTaskCode"
          label="分料任务号"
          rules={[{ required: true, message: 'Please input your pickingTaskCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="positionNo"
          label="位置号"
          rules={[{ required: true, message: 'Please input your positionNo!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processCode"
          label="所属工序"
          rules={[{ required: true, message: 'Please input your processCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="serialNum"
          label="序列"
          rules={[{ required: true, message: 'Please input your serialNum!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="serialNumGroup"
          label="序列号组"
          rules={[{ required: true, message: 'Please input your serialNumGroup!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="unit"
          label="单位"
          rules={[{ required: true, message: 'Please input your unit!' }]}
          disabled={createOrUpdate}
        />
      </ModalForm>
    </>
  );
});
export default PickingDetails;
